import React, { useReducer } from 'react'
// 注意: useReducer语法看起来和redux一样.但是其实不是redux.是定义组件的状态数据.
// 好处: 可以把组件中的所有状态数据,集中管理在一个对象中
export default function App() {
  console.log('app执行了')
  function reducer(state, action) {
    switch (action.type) {
      case 'add':
        return {
          ...state,
          count: state.count + 1,
        }

      case 'setmsg':
        return {
          ...state,
          msg: action.payload,
        }
    }
  }
  const [state, dispatch] = useReducer(reducer, {
    count: 0,
    msg: 'hello useReducer',
  })
  return (
    <div>
      App
      <p>{state.msg}</p>
      <p>{state.count}</p>
      <button
        onClick={() => {
          // dispatch调用,会导致reducer函数执行,会修改状态数据.一旦状态数据发生变化,则组件更新
          dispatch({ type: 'add' })
        }}
      >
        +
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'setmsg', payload: '嘿嘿嘿' })
        }}
      >
        setMsg
      </button>
    </div>
  )
}
